package com.guli.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guli.gulimall.product.dao.AttrDao;
import com.guli.gulimall.product.entity.AttrEntity;
import com.guli.gulimall.product.entity.vo.AttrGroupVo;
import com.guli.gulimall.product.util.CategoryUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;
import com.guli.gulimall.product.dao.AttrGroupDao;
import com.guli.gulimall.product.entity.AttrGroupEntity;
import com.guli.gulimall.product.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private CategoryUtil categoryUtil;

    @Autowired
    private AttrDao attrDao;

    @Override
    public AttrGroupEntity getById(Serializable id) {
        AttrGroupEntity attrGroupEntity = baseMapper.selectById(id);
        Long catalogId = attrGroupEntity.getCatalogId();
        Long[] ids = categoryUtil.getCatalogIds(catalogId);
        attrGroupEntity.setCatalogPath(ids);
        return attrGroupEntity;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params,Long catalogId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        if (catalogId != 0) {
            wrapper.eq("catalog_id",catalogId);
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<AttrGroupVo> withAttrList(Long catalogId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catalog_id",catalogId);
        List<AttrGroupEntity> attrGroupList = baseMapper.selectList(wrapper);

        List<AttrGroupVo> collect = attrGroupList.stream().map(item -> {
            AttrGroupVo attrGroupVo = new AttrGroupVo();
            BeanUtils.copyProperties(item, attrGroupVo);

            List<AttrEntity> attrs = attrDao.selectList(new QueryWrapper<AttrEntity>().eq("attr_type", 1)
                    .eq("attr_group_id", item.getAttrGroupId()));

            attrGroupVo.setAttrs(attrs);
            return attrGroupVo;
        }).collect(Collectors.toList());
        return collect;
    }

}